import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_collection.dart';
import 'package:tender_flutter/page/home/model/certification_entity.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

import 'item/my_collection_certification_cell.dart';

/// 资质收藏列表
class CollectionCertificationPage extends StatefulWidget {
  @override
  _CollectionCertificationPageState createState() =>
      _CollectionCertificationPageState();
}

class _CollectionCertificationPageState
    extends State<CollectionCertificationPage>
    with AutomaticKeepAliveClientMixin {
  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  LoadState _loadState = LoadState.State_Loading;

  Future<ApiResponse<CertificationListEntity>> _listFuture;

  /// 数据列表
  List<CertificationEntity> _dataLists = [];

  /// 页码
  int page = AppConfig.page;

  /// 收藏/取消
  /// 返回是否请求成功的状态
  Future<bool> _setCollection({String cerId}) async {
    var response = await ApiCollection.certificationCollection(cerId: cerId);
    ToastUtils.show(response.msg);
    return response.status == Status.SUCCESS ? true : false;
  }

  /// 获取数据
  Future<ApiResponse<CertificationListEntity>> _getData() async {
    var response = await ApiPerson.getMyCollection<CertificationListEntity>(
      type: 4,
      page: page,
    );

    if (_refreshController.isLoading) {
      _refreshController.loadComplete();
    }
    if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
    return response;
  }

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }
    setState(() {
      _listFuture = _getData();
    });
  }

  FutureBuilder<ApiResponse<CertificationListEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        // ignore: missing_return
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<CertificationListEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              CertificationListEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initListView(),
          );
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      body: _buildFutureBuilder(),
    );
  }

  /// 主体内容列表
  Widget _initListView() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _refresh,
        onLoading: _refresh,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            CertificationEntity model = _dataLists[index];
            return CollectionCertificateListCell(
                data: model,
                onCancelCallback: () async {
                  bool success = await _setCollection(cerId: model.key);
                  if (success) {
                    setState(() {
                      _dataLists.remove(index);
                    });
                  }
                },
                onClickCallback: () {
                  LRouter.navigatorCtx(context).push(
                      Routes.certificateDetailPage,
                      arguments: CertificateDetailPageArguments(
                          certId: model.Id, companyName: model.CompanyName));
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType49,
            );
          },
        ));
  }
}
